#include "stdafx.h"
#include "service\storage\file\SystemFileService.h"
#include "lib\TCollection.h"
#include "lib\ErrorHandler.h"
#include "model\Player.h"
#include "model\Sport.h"


SystemFileService::SystemFileService() {

}

SystemFileService::SystemFileService(const std::string fname,
                    const std::ios::openmode mode)
    : BaseFileService(fname, mode) {

}

SystemFileService::SystemFileService(std::fstream& file) : BaseFileService(file) {

}

SystemFileService::~SystemFileService() {

}


SystemFileService& SystemFileService::LoadState(TCollection<Player>* players) {
  Player player;
  while (file() >> player) {
    if (player.Validate()) {
      players->Add(player);
    } else {
      ErrorHandler::DisplayError("Error: An unexpected error occurred while "
                                 "loading player from file.");
    }
  }
  return *this;
}


SystemFileService& SystemFileService::LoadState(TCollection<Sport>* sports) {
  Sport sport;
  while (file() >> sport) {
    if (sport.Validate()) {
      sports->Add(sport);
    } else {
      ErrorHandler::DisplayError("Error: An unexpected error occurred while "
        "loading sport from file.");
    }
  }
  return *this;
}

SystemFileService& SystemFileService::SaveState(const TCollection<Player>* players) {
  TCollection<Player>::CollectionPair iters = players->GetCollection();
  for (; iters.first != iters.second; ++iters.first)
    file() << *iters.first << '\n';
  return *this;
}

SystemFileService& SystemFileService::SaveState(const TCollection<Sport>* sports) {
  TCollection<Sport>::CollectionPair sportiters = sports->GetCollection();
  for (; sportiters.first != sportiters.second; ++sportiters.first)
    file() << *sportiters.first << '\n';
  return *this;
}